package cn.bookcycle.panda.user.dao.impl;

import cn.bookcycle.panda.user.dao.AuthsDao;
import cn.bookcycle.panda.user.util.Dao;
import cn.bookcycle.panda.user.pojo.DO.AuthsDO;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AuthsDaoImpl implements AuthsDao {
    @Autowired
    Dao<AuthsDO> authsDao;
    @Override
    public AuthsDO getAuths(String identifier,String credential,String type) {
        AuthsDO authsDO =new AuthsDO();
        authsDO.setIdentifier(identifier);
        authsDO.setCredential(credential);
        authsDO.setType(type);
        String result = authsDao.daoMethod("auths", "find","ExactMatch", authsDO);
        return this.transferResult(result);
    }


    @Override
    public AuthsDO getAuthsByUserId(String userId) {
        AuthsDO authsDO =new AuthsDO();
        authsDO.setId(userId);
        String result = authsDao.daoMethod("auths", "find","ExactMatch", authsDO);
        return this.transferResult(result);
    }

    @Override
    public boolean updateAuths(AuthsDO authsDO) {
        try {
            String result = authsDao.daoMethod("auths", "update","ExactMatch", authsDO);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    @Override
    public boolean saveAuths(AuthsDO authsDO) {
        try {
            String result = authsDao.daoMethod("auths", "insert","ExactMatch", authsDO);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    @Override
    public boolean removeAuths(AuthsDO authsDO) {
        try {
            String result = authsDao.daoMethod("auths", "remove","ExactMatch", authsDO);
            return true;
        }catch (Exception e){
            return false;
        }
    }
    @Override
    public List listAuths(AuthsDO authsDO){
        try {
            String result=authsDao.daoMethod("user","find","ExactMatch",authsDO);
            JSONArray jsonArray = JSONArray.fromObject(result);
            List userDOList=(List)JSONArray.toCollection(jsonArray,authsDO.getClass());
            return  userDOList;
        }catch (Exception e){
            return null;
        }
    }

    private AuthsDO transferResult(String result){
        if (result == null||"".equals(result)) {
            return null;
        } else {
            if (JSONArray.fromObject(result).size() > 1) {
                return null;
            } else {
                Object authsObject = JSONArray.fromObject(result).get(0);
                AuthsDO authsDO = (AuthsDO) JSONObject.toBean(JSONObject.fromObject(authsObject), AuthsDO.class);
                return authsDO;
            }
        }
    }

}
